/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sane;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author pjl
 */
public class Builder {

    static Network build(Gene list[], Context c) {

       
        Network net = new Network(c.nIn, c.nHidden, c.nOut);

        Temp hid = new Temp(c.nHidden);
        Temp out = new Temp(c.nOut);

  //      int nTot = nIn + nOut;

        int bitsPerConnection=24;
        int iHid=0;
        for (Gene gene : list) {

            for (int i = 0; i < c.nConnect ; i++) {
                int start=i*bitsPerConnection;
                float w = gene.floatAt(start,16,3);
                int ptr = gene.unsignedAt(start+16, 8);
              
                if (ptr < 128) {
                    ptr = ptr%c.nOut;
                    out.add(ptr, iHid, w);
           //         System.out.println(" Add hid["+iHid+"]->out["+ptr+"] " + w);
                } else {
                    ptr=(ptr-128)%c.nIn;
                    hid.add(iHid, ptr, w);
         //           System.out.println(" Add in["+ptr+"]->hid["+iHid + "] " + w);
                }
            }
            iHid++;
        }

        for(int i=0;i<c.nHidden;i++) {
            net.addHidden(hid.ptrA.get(i),hid.wA.get(i),i);
        }

        for(int i=0;i<c.nOut;i++) {
            net.addOut(out.ptrA.get(i),out.wA.get(i),i);
        }

        return net;
    }

    static class Temp {

        ArrayList<ArrayList<Float>> wA;
        ArrayList<ArrayList<Integer>> ptrA;

        Temp(int n) {

            wA = new ArrayList<ArrayList<Float>>();
            ptrA = new ArrayList<ArrayList<Integer>>();

            for (int i = 0; i < n; i++) {
                wA.add(new ArrayList<Float>());
                ptrA.add(new ArrayList<Integer>());
            }
        }

        void add(int i, Integer ptr, Float w) {
            wA.get(i).add(w);
            ptrA.get(i).add(ptr);
        }
    }
}
